package cn.edu.zust.se.service.file.utils;


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;


import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class RedisUtil {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    //写入对象
    public boolean setObject(final String key, Object value, Integer expireTime) {
        try {

            redisTemplate.opsForValue().set(key, value);
            redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    //获取对象
    public Object getObject(final String key) {
        System.out.println("key1:" + key);
        Object o = redisTemplate.opsForValue().get(key);
        log.info("o:" + o);
        return o;
    }


    //写入集合
    public boolean setList(final String key, Object value, Integer expireTime) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    //获取集合
    public List<Object> getList(final String key) {
        try {
            return redisTemplate.opsForList().range(key, 0, -1);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    //判断时候存在key
    public boolean hasKey(final String key) {
        try {
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    //删除key
    public void del(final String key) {
        if (hasKey(key)) {
            redisTemplate.delete(key);
        }
    }


    public Boolean getLock(String key) {
        // 1.获取锁
        Boolean result = stringRedisTemplate.opsForValue().setIfAbsent(key, String.valueOf(1), 10, TimeUnit.SECONDS);
        if (!result) {
           //等待解锁,线程休眠
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            getLock(key);
        }
        return true;
    }

    public void releaseLock(String key) {
        // 1.释放锁
        stringRedisTemplate.delete(key);

    }


}
